package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-01-02
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }
    //入住申请
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto checkInApplyDto) {
        //1.校验老人是否已经入住
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        wrapper.eq(Elder::getIdCardNo,checkInElderDto.getIdCardNo())
                .in(Elder::getStatus,1,4);
        Elder elder = elderMapper.selectOne(wrapper);
        //2.如果已经入住退出方法
        if(ObjectUtil.isNotEmpty(elder)){
            throw new BaseException("老人已经入住");
        }
        //3.如果没入住更新床位状态
        Long bedId = checkInApplyDto.getCheckInConfigDto().getBedId();
        Bed bed = bedMapper.selectById(bedId);
        bed.setBedStatus(1);
        bedMapper.updateBed(bed);

        //4.新增或更新老人信息
        elder= insertOrUpdate(checkInElderDto, bed);
        //5.新增签约办理
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        insertContract(checkInContractDto,checkInApplyDto.getCheckInConfigDto(), elder);

        //6.新增入住信息（以及家属信息封装到remark字段中）
        CheckIn checkIn = insertCheckInfo(elder,checkInApplyDto.getCheckInConfigDto(),bed,checkInApplyDto.getElderFamilyDtoList());
        //7.新增入住配置
        insertConfig(checkIn,checkInApplyDto.getCheckInConfigDto());
    }

    private void insertConfig(CheckIn checkIn, CheckInConfigDto checkInConfigDto) {

        CheckInConfig config = new CheckInConfig();
        config.setCheckInId(checkIn.getId());
        BeanUtils.copyProperties(checkInConfigDto, config);
        checkInConfigMapper.insert(config);
    }

    private CheckIn insertCheckInfo(Elder elder, CheckInConfigDto checkInConfigDto, Bed bed, List<ElderFamilyDto> elderFamilyDtoList) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSON.toJSONString(elderFamilyDtoList));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    private void insertContract(CheckInContractDto checkInContractDto, CheckInConfigDto checkInConfigDto, Elder elder) {
        Contract contract = new Contract();
        contract.setElderId(Integer.valueOf(String.valueOf(elder.getId())));
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        BeanUtils.copyProperties(checkInContractDto, contract);
        contractMapper.insert(contract);

    }

    public Elder insertOrUpdate(CheckInElderDto checkInElderDto,Bed bed) {
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper();
        wrapper.eq(Elder::getIdCardNo,checkInElderDto.getIdCardNo());
        Elder elder = elderMapper.selectOne(wrapper);
        if(ObjectUtil.isEmpty(elder)){
            elder = new Elder();
            BeanUtils.copyProperties(checkInElderDto, elder);
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());
            elder.setStatus(1);
            elderMapper.insert(elder);
            return elder;
        }else {
            BeanUtils.copyProperties(checkInElderDto, elder);
            elder.setBedId(bed.getId());
            elder.setBedNumber(bed.getBedNumber());
            elder.setStatus(1);
            elderMapper.updateById(elder);
            return elder;
        }
    }

    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckIn checkIn = checkInMapper.selectById(id);
        ElderFamilyVo elderFamilyVo = new ElderFamilyVo();
        Object parse = JSON.parse(checkIn.getRemark());
        List<ElderFamilyVo> list = JSON.parseArray(JSON.toJSONString(parse), ElderFamilyVo.class);
        BeanUtils.copyProperties(parse,elderFamilyVo);

        Elder elder = elderMapper.selectOne(Wrappers.lambdaQuery(Elder.class).eq(Elder::getId, checkIn.getElderId()));
        CheckInElderVo checkInElderVo = new CheckInElderVo();
//        LocalDate currentDate = LocalDate.now();
//        Period period = Period.between(LocalDate.parse(elder.getBirthday()), currentDate);
//        int age = period.getYears();
        int age = IdcardUtil.getAgeByIdCard(elder.getIdCardNo(), DateTime.now());
//        DateUtil.ageOfNow(elder.getBirthday());
        checkInElderVo.setAge(age);
        BeanUtils.copyProperties(elder,checkInElderVo);

        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.lambdaQuery(CheckInConfig.class).eq(CheckInConfig::getCheckInId, checkIn.getId()));
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);

        Contract contract = contractMapper.selectOne(Wrappers.lambdaQuery(Contract.class).eq(Contract::getElderId, elder.getId()));
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo(checkInElderVo,list,checkInConfigVo,contract);
        return checkInDetailVo;
    }

}
